﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EC_ASS.Models;
using System.Text;
using PagedList;

namespace EC_ASS.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            BigModel bigModel = new BigModel();
            DataECDataContext context = new DataECDataContext();
            bigModel.PAProduct = (from c in context.Categories
                                  join p in context.Products on c.ID equals p.CatID
                                  where c.Prefix == "PA"
                                  orderby p.InsertDate descending
                                  select p).Take(6);
            bigModel.PQProduct = (from c in context.Categories
                                  join p in context.Products on c.ID equals p.CatID
                                  where c.Prefix == "PQ"
                                  orderby p.InsertDate descending
                                  select p).Take(6);
            bigModel.PGProduct = (from c in context.Categories
                                  join p in context.Products on c.ID equals p.CatID
                                  where c.Prefix == "PG"
                                  orderby p.InsertDate descending
                                  select p).Take(6);
            // Get deals
            bigModel.Deals = (from d in context.Product_Deals
                              join p in context.Products on d.ID equals p.ID
                              select new DealsModel
                              {
                                  DealResult = p,
                                  Discount = d.Discount,
                                  ExpiredTime = d.ExpiredTime
                              }).ToList();
            
            return View(bigModel);
        }

        public ActionResult Search(string key, int page = 1)
        {
            BigModel bigModel = new BigModel();
            DataECDataContext context = new DataECDataContext();

            // Chuyển chuỗi search ve tiếng việt không dấu
            string searchKey = ToSearchKey(key).ToLower();

            var resultList = (from c in context.Categories
                              join p in context.Products on c.ID equals p.CatID
                              select new SearchResultModel { ProductResult = p, CategoryPrefix = c.Prefix }).ToList();

            // Tìm kiếm theo tiếng việt không dấu.
            var PAProduct = resultList.FindAll(delegate(SearchResultModel match)
            {
                if (!(String.IsNullOrEmpty(searchKey)))
                {
                    if (ToSearchKey(match.ProductResult.Name).ToLower().Contains(searchKey))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            });
            ViewBag.Key = key;
            // Phân trang dữ liệu
            return View(PAProduct.ToPagedList(page, 24));
        }

        public ActionResult Detail() {
            return View();
        }

        //Load new T-shirt
        public ActionResult TShirt()
        {
            DataECDataContext context = new DataECDataContext();
            var listTShirt = context.Products.Where(p => p.CatID == 1 || p.CatID == 2 || p.CatID == 3
                || p.CatID == 4);
            ViewBag.MSM = "Danh sách sản phẩm mới";
            return View(listTShirt.ToList());
        }

        //Load new shoes
        public ActionResult Shoes()
        {
            DataECDataContext context = new DataECDataContext();
            var listShoes = context.Products.Where(p => p.CatID == 9 || p.CatID == 10 || p.CatID == 11);
            ViewBag.MSM = "Danh sách sản phẩm mới";
            return View(listShoes.ToList());
        }

        //Load new shoes
        public ActionResult Pants()
        {
            DataECDataContext context = new DataECDataContext();
            var listPants = context.Products.Where(p => p.CatID == 5 || p.CatID == 6 || p.CatID == 7 || p.CatID == 8);
            ViewBag.MSM = "Danh sách sản phẩm mới";
            return View(listPants.ToList());
        }

        // Load category
        [ChildActionOnly]
        public ActionResult _Header()
        {
            BigModel myModel = new BigModel();
            DataECDataContext context = new DataECDataContext();
            // Áo
            myModel.PA = (from c in context.Categories where c.Prefix == "PA" select c).ToList();
            // Quần
            myModel.PQ = (from c in context.Categories where c.Prefix == "PQ" select c).ToList();
            // Giày
            myModel.PG = (from c in context.Categories where c.Prefix == "PG" select c).ToList();
            // Phụ kiện
            myModel.PK = (from c in context.Categories where c.Prefix == "PK" select c).ToList();
            return PartialView("_Header", myModel);
        }

        public ActionResult Buy()
        {
            return View();
        }

        // Contact page
        public ActionResult ContactUS()
        {
            return View();
        }

        // Feeback
        [HttpPost]
        public ActionResult Feedback(FormCollection form)
        {
            DataECDataContext context = new DataECDataContext();
            Feedback feedback = new Feedback();
            // Create Feedback object
            feedback.Customer = (string) form.Get("customer");
            feedback.Email = (string)form.Get("email");
            feedback.Time = DateTime.Now;
            feedback.Content = (string) form.Get("content");
            // Add to database
            try
            {
                context.Feedbacks.InsertOnSubmit(feedback);
                context.SubmitChanges();

                // Get message
                ViewBag.MSM = "Gửi feedback thành công! Cám ơn bạn đã góp ý cho chúng tôi.";
            }
            catch (System.Exception ex)
            {
                ViewBag.MSM = "Có lỗi phát sinh. Vui lòng thử lại.";
            }
            return PartialView("SendFeedback", "Home");
        }
      
        // Đưa các search key về tiếng việt không dấu để tìm
        private string ToSearchKey(string keyword)
        {
            string stFormD = keyword.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();
            for (int ich = 0; ich < stFormD.Length; ich++)
            {
                System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
                if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
                {
                    sb.Append(stFormD[ich]);
                }
            }
            sb = sb.Replace('Đ', 'D');
            sb = sb.Replace('đ', 'd');
            return (sb.ToString().Normalize(NormalizationForm.FormD).ToUpperInvariant().Trim().Replace(" ", "-"));
        }
    }
}
